<template>
  <div>
    <el-card shadow="never">
      <el-skeleton :loading="loading" animated>
        <el-row :gutter="16" justify="space-between">
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="flex items-center">
              <el-avatar :src="avatar" :size="70" class="mr-16px">
                <img src="@/assets/imgs/avatar.gif" alt="" />
              </el-avatar>
              <div>
                <div class="text-20px">
                  {{ t('workplace.welcome') }} {{ username }} {{ t('workplace.happyDay') }}
                </div>
                <div class="mt-10px text-14px text-gray-500">
                  {{ t('workplace.toady') }}，20℃ - 32℃！
                </div>
              </div>
            </div>
          </el-col>
          <el-col :xl="12" :lg="12" :md="12" :sm="24" :xs="24">
            <div class="h-70px flex items-center justify-end lt-sm:mt-10px">
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.project') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.project"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.toDo') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.todo"
                  :duration="2600"
                />
              </div>
              <el-divider direction="vertical" border-style="dashed" />
              <div class="px-8px text-right">
                <div class="mb-16px text-14px text-gray-400">{{ t('workplace.access') }}</div>
                <CountTo
                  class="text-20px"
                  :start-val="0"
                  :end-val="totalSate.access"
                  :duration="2600"
                />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-skeleton>
    </el-card>
  </div>

  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <!-- 设备地图组件 -->
      <div class="map-wrapper">
        <DeviceMap />
      </div>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <div class="charts-wrapper">
        <!-- CPU使用率图表 -->
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="h-3 flex justify-between">
              <span>CPU使用率</span>
            </div>
          </template>
          <el-skeleton :loading="systemLoading" animated>
            <div ref="cpuChartRef" class="chart-container"></div>
          </el-skeleton>
        </el-card>

        <!-- 内存使用率图表 -->
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="h-3 flex justify-between">
              <span>内存使用率</span>
            </div>
          </template>
          <el-skeleton :loading="systemLoading" animated>
            <div ref="memoryChartRef" class="chart-container"></div>
          </el-skeleton>
        </el-card>

        <!-- 磁盘使用率图表 -->
        <el-card shadow="never" class="chart-card">
          <template #header>
            <div class="h-3 flex justify-between">
              <span>系统盘使用率</span>
            </div>
          </template>
          <el-skeleton :loading="systemLoading" animated>
            <div ref="diskChartRef" class="chart-container"></div>
          </el-skeleton>
        </el-card>
      </div>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { set } from 'lodash-es'
import { EChartsOption } from 'echarts'
import { formatTime } from '@/utils'
import * as echarts from 'echarts'

import { useUserStore } from '@/store/modules/user'
// import { useWatermark } from '@/hooks/web/useWatermark'
import type { WorkplaceTotal, Project, Notice, Shortcut } from './types'
import { pieOptions, barOptions } from './echarts-data'
import { useRouter } from 'vue-router'
import DeviceMap from './DeviceMap.vue'
import { SystemConfigApi, type SystemUsageVO } from '@/api/mqtt/systemconfig'

defineOptions({ name: 'Index' })

const { t } = useI18n()
const router = useRouter()
const userStore = useUserStore()
// const { setWatermark } = useWatermark()
const loading = ref(true)
const systemLoading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const pieOptionsData = reactive<EChartsOption>(pieOptions) as EChartsOption

// 系统监控图表相关
const cpuChartRef = ref()
const memoryChartRef = ref()
const diskChartRef = ref()
let cpuChart: echarts.ECharts
let memoryChart: echarts.ECharts
let diskChart: echarts.ECharts
// 获取统计数
let totalSate = reactive<WorkplaceTotal>({
  project: 0,
  access: 0,
  todo: 0
})

const getCount = async () => {
  const data = {
    project: 40,
    access: 2340,
    todo: 10
  }
  totalSate = Object.assign(totalSate, data)
}

// 获取项目数
let projects = reactive<Project[]>([])
const getProject = async () => {
  const data = [
    {
      name: '',
      icon: 'icon-park-outline:mall-bag',
      message: '',
      personal: '',
      time: new Date('2025-03-04'),
      color: '#ff4d4f'
    },
    {
      name: '',
      icon: 'icon-park-outline:mall-bag',
      message: '',
      personal: '',
      time: new Date('2025-03-04'),
      color: '#ff4d4f'
    },
    {
      name: '',
      icon: 'icon-park-outline:mall-bag',
      message: '',
      personal: '',
      time: new Date('2025-03-04'),
      color: '#ff4d4f'
    },
    {
      name: '',
      icon: 'icon-park-outline:mall-bag',
      message: '',
      personal: '',
      time: new Date('2025-03-04'),
      color: '#ff4d4f'
    },
    {
      name: '',
      icon: 'icon-park-outline:mall-bag',
      message: '',
      personal: '',
      time: new Date('2025-03-04'),
      color: '#ff4d4f'
    },
    {
      name: '',
      icon: 'icon-park-outline:mall-bag',
      message: '',
      personal: '',
      time: new Date('2025-03-04'),
      color: '#ff4d4f'
    }
  ]
  projects = Object.assign(projects, data)
}

// 获取通知公告（已移除，不再使用）
// let notice = reactive<Notice[]>([])
// const getNotice = async () => {
//   const data = [
//     {
//       title: '系统支持 JDK 8/17/21，Vue 2/3',
//       type: '技术兼容性',
//       keys: ['JDK', 'Vue'],
//       date: new Date()
//     }
//   ]
//   notice = Object.assign(notice, data)
// }

// 获取快捷入口（已移除，不再使用）
// let shortcut = reactive<Shortcut[]>([])

// const getShortcut = async () => {
//   const data = [
//     {
//       name: '首页',
//       icon: 'ion:home-outline',
//       url: '/',
//       color: '#1fdaca'
//     },
//     {
//       name: '商城中心',
//       icon: 'ep:shop',
//       url: '/mall/home',
//       color: '#ff6b6b'
//     },
//     {
//       name: 'AI 大模型',
//       icon: 'tabler:ai',
//       url: '/ai/chat',
//       color: '#7c3aed'
//     },
//     {
//       name: 'ERP 系统',
//       icon: 'simple-icons:erpnext',
//       url: '/erp/home',
//       color: '#3fb27f'
//     },
//     {
//       name: 'CRM 系统',
//       icon: 'simple-icons:civicrm',
//       url: '/crm/backlog',
//       color: '#4daf1bc9'
//     },
//     {
//       name: 'IoT 物联网',
//       icon: 'fa-solid:hdd',
//       url: '/iot/home',
//       color: '#1a73e8'
//     }
//   ]
//   shortcut = Object.assign(shortcut, data)
// }

// 用户来源
const getUserAccessSource = async () => {
  const data = [
    { value: 335, name: 'analysis.directAccess' },
    { value: 310, name: 'analysis.mailMarketing' },
    { value: 234, name: 'analysis.allianceAdvertising' },
    { value: 135, name: 'analysis.videoAdvertising' },
    { value: 1548, name: 'analysis.searchEngines' }
  ]
  set(
    pieOptionsData,
    'legend.data',
    data.map((v) => t(v.name))
  )
  pieOptionsData!.series![0].data = data.map((v) => {
    return {
      name: t(v.name),
      value: v.value
    }
  })
}
const barOptionsData = reactive<EChartsOption>(barOptions) as EChartsOption

// 周活跃量
const getWeeklyUserActivity = async () => {
  const data = [
    { value: 13253, name: 'analysis.monday' },
    { value: 34235, name: 'analysis.tuesday' },
    { value: 26321, name: 'analysis.wednesday' },
    { value: 12340, name: 'analysis.thursday' },
    { value: 24643, name: 'analysis.friday' },
    { value: 1322, name: 'analysis.saturday' },
    { value: 1324, name: 'analysis.sunday' }
  ]
  set(
    barOptionsData,
    'xAxis.data',
    data.map((v) => t(v.name))
  )
  set(barOptionsData, 'series', [
    {
      name: t('analysis.activeQuantity'),
      data: data.map((v) => v.value),
      type: 'bar'
    }
  ])
}

const getAllApi = async () => {
  await Promise.all([
    getCount(),
    getProject(),
    // getNotice(), // 已移除
    // getShortcut(), // 已移除
    getUserAccessSource(),
    getWeeklyUserActivity()
  ])
  loading.value = false
}

const handleProjectClick = (message: string) => {
  window.open(`https://${message}`, '_blank')
}

const handleShortcutClick = (url: string) => {
  router.push(url)
}

// 初始化系统监控图表
const initSystemCharts = () => {
  // 检查DOM元素是否存在
  if (!cpuChartRef.value || !memoryChartRef.value || !diskChartRef.value) {
    setTimeout(initSystemCharts, 50)
    return
  }

  try {
    cpuChart = echarts.init(cpuChartRef.value)
    memoryChart = echarts.init(memoryChartRef.value)
    diskChart = echarts.init(diskChartRef.value)
  } catch (error) {
    console.error('初始化系统监控图表失败:', error)
  }
}

// 更新系统监控图表
const updateSystemCharts = (data: SystemUsageVO) => {
  // 检查图表实例是否存在
  if (!cpuChart || !memoryChart || !diskChart) {
    return
  }

  // CPU使用率图表
  cpuChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)'
    },
    series: [
      {
        name: 'CPU使用率',
        type: 'pie',
        radius: ['25%', '55%'], // 调整扇形图大小
        center: ['50%', '50%'],
        data: [
          { value: data.cpu.used, name: '已用', itemStyle: { color: '#ff4757' } },
          { value: data.cpu.free, name: '空闲', itemStyle: { color: '#f1f2f6' } }
        ],
        label: {
          show: true,
          formatter: '{b}: {c}%',
          fontSize: 11,
          color: '#666'
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 5
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 8,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      }
    ]
  })

  // 内存使用率图表
  memoryChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)'
    },
    series: [
      {
        name: '内存使用率',
        type: 'pie',
        radius: ['25%', '55%'], // 调整扇形图大小
        center: ['50%', '50%'],
        data: [
          { value: data.memory.used, name: '已用', itemStyle: { color: '#ff6b6b' } },
          { value: data.memory.free, name: '剩余', itemStyle: { color: '#f1f2f6' } }
        ],
        label: {
          show: true,
          formatter: '{b}: {c}%',
          fontSize: 11,
          color: '#666'
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 5
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 8,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      }
    ]
  })

  // 磁盘使用率图表
  diskChart.setOption({
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c}% ({d}%)'
    },
    series: [
      {
        name: '磁盘使用率',
        type: 'pie',
        radius: ['25%', '55%'], // 调整扇形图大小
        center: ['50%', '50%'],
        data: [
          { value: data.disk.used, name: '已用', itemStyle: { color: '#ffa502' } },
          { value: data.disk.free, name: '可用', itemStyle: { color: '#f1f2f6' } }
        ],
        label: {
          show: true,
          formatter: '{b}: {c}%',
          fontSize: 11,
          color: '#666'
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 5
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 8,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.3)'
          }
        }
      }
    ]
  })
}

// 获取系统使用率数据
const getSystemUsage = async () => {
  try {
    systemLoading.value = true
    const res = await SystemConfigApi.getSystemUsage()
    console.log('---------------->>>>res', res)

    // 后端现在返回标准的CommonResult格式，直接使用data字段
    const data: SystemUsageVO = res.data || res

    console.log('解析后的数据:', data)

    if (cpuChart && memoryChart && diskChart) {
      updateSystemCharts(data)
    } else {
      setTimeout(() => {
        if (cpuChart && memoryChart && diskChart) {
          updateSystemCharts(data)
        }
      }, 200)
    }
  } catch (error) {
    console.error('获取系统使用率失败:', error)
  } finally {
    systemLoading.value = false
  }
}

// 刷新系统使用率
const refreshSystemUsage = () => {
  getSystemUsage()
}

// 生命周期钩子
onMounted(() => {
  // 延迟初始化，确保DOM完全渲染
  setTimeout(() => {
    initSystemCharts()
    // 图表初始化完成后再获取数据
    setTimeout(() => {
      getSystemUsage()
    }, 100)
  }, 100)
})

onUnmounted(() => {
  cpuChart?.dispose()
  memoryChart?.dispose()
  diskChart?.dispose()
})

getAllApi()
</script>

<style scoped>
.map-wrapper {
  height: 700px;
  min-height: 600px;
  display: flex;
  flex-direction: column;
}

.map-wrapper :deep(.map-container) {
  flex: 1;
  height: 100% !important;
}

.map-wrapper :deep(.map-content) {
  height: 100% !important;
  min-height: 100% !important;
  image-rendering: -webkit-optimize-contrast;
  image-rendering: crisp-edges;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.charts-wrapper {
  height: 700px;
  min-height: 600px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chart-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  width: 100%;
  min-height: 0;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .map-wrapper,
  .charts-wrapper {
    height: auto;
    min-height: 500px;
  }

  .chart-card {
    margin-bottom: 8px;
  }
}
</style>
